package excel

import (
	"gitee.com/DengAnbang/Computation/src/bean"
)

type TreeNodeManage struct {
	RootTreeNode *TreeNode
	LastTreeNode *TreeNode
	relationMap  map[string]*TreeNode //所有父节点的集合,方便添加查找数据
}

type TreeNode struct {
	Depth        int //当前节点的深度
	ThisTreeBean *bean.TreeBean
	ChildNodes   []*TreeNode //子节点的集合
	ParentNode   *TreeNode
}

func NewTreeNodeManage() TreeNodeManage {
	return TreeNodeManage{
		relationMap: make(map[string]*TreeNode),
	}
}
func (t *TreeNodeManage) IsEmpty() bool {
	return t.RootTreeNode == nil
}

func (t *TreeNodeManage) AddTreeNode(child *TreeNode, parent *TreeNode) {
	child.Depth = parent.Depth + 1
	child.ParentNode = parent
	parent.ChildNodes = append(parent.ChildNodes, child)
	t.LastTreeNode = child
}

//func (t *TreeNodeManage) AddTreeNode(child bean.TreeBean, parent *TreeNode) {
//	node := TreeNode{
//		Depth:        parent.Depth + 1,
//		ThisTreeBean: &child,
//		ChildNodes:   make([]TreeNode, 0),
//		ParentNode:   parent,
//	}
//	parent.ChildNodes = append(parent.ChildNodes, node)
//	t.LastTreeNode = &node
//	t.relationMap[child.NodeId] = &node
//}
func (t *TreeNodeManage) GetParentByDepth(depth int) *TreeNode {
	lastDepth := t.LastTreeNode.Depth
	if lastDepth == depth {
		return t.LastTreeNode.ParentNode
	} else if lastDepth < depth {
		return t.LastTreeNode
	}
	parent := t.LastTreeNode
	for parent.Depth != depth {
		parent = parent.ParentNode
	}
	return parent.ParentNode
}

func (t *TreeNodeManage) SetRootNode(treeBean *bean.TreeBean) {
	node := &TreeNode{
		Depth:        0,
		ThisTreeBean: treeBean,
		ChildNodes:   make([]*TreeNode, 0),
	}
	t.RootTreeNode = node
	t.LastTreeNode = node
}

func (t *TreeNodeManage) CreateTree(beans []bean.TreeBean) {
	//第一次循环,将所有的节点都当成父节点,加入到relationMap中,方便第二次将子节点挂到父节点上
	for _, v := range beans {
		var thisTreeBean = v
		if v.NodeId != t.RootTreeNode.ThisTreeBean.NodeId {
			t.relationMap[v.NodeId] = &TreeNode{
				ThisTreeBean: &thisTreeBean,
				ChildNodes:   make([]*TreeNode, 0),
			}
		} else {
			t.relationMap[v.NodeId] = t.RootTreeNode
		}
	}
	for _, v := range beans {
		if v.NodeId != t.RootTreeNode.ThisTreeBean.NodeId {
			parentNode := t.relationMap[v.NodeParentId]
			thisNode := t.relationMap[v.NodeId]

			t.AddTreeNode(thisNode, parentNode)
		}
	}
}
func (t *TreeNodeManage) Beans() []bean.TreeBean {
	beans := make([]bean.TreeBean, 0)
	beans = appendChild(beans, *t.RootTreeNode)
	return beans
}
func appendChild(bean []bean.TreeBean, t TreeNode) []bean.TreeBean {
	bean = append(bean, *t.ThisTreeBean)
	for _, v := range t.ChildNodes {
		bean = appendChild(bean, *v)
	}
	return bean
}
